package com.ruoyi.deal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.deal.bo.HyDealOrderQueryBo;
import com.ruoyi.deal.domain.HyDealGoods;
import com.ruoyi.deal.domain.HyDealOrder;
import com.ruoyi.deal.mapper.HyDealOrderMapper;
import com.ruoyi.deal.service.IHyDealGoodsService;
import com.ruoyi.deal.service.IHyDealOrderService;
import com.ruoyi.system.domain.HyUser;
import com.ruoyi.system.service.IHyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 交易订单Service业务层处理
 *
 * @author lixin
 * @date 2021-07-19
 */
@Service
public class HyDealOrderServiceImpl extends ServicePlusImpl<HyDealOrderMapper, HyDealOrder> implements IHyDealOrderService {

	@Autowired
	private IHyDealGoodsService dealGoodsService;

	@Autowired
	private IHyUserService userService;

    @Override
    public HyDealOrder queryById(Long orderId){
        return getById(orderId);
    }

    @Override
    public TableDataInfo<HyDealOrder> queryPageList(HyDealOrderQueryBo bo) {
        PagePlus<HyDealOrder, HyDealOrder> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), HyDealOrder.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<HyDealOrder> queryList(HyDealOrderQueryBo bo) {
        return list(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<HyDealOrder> buildQueryWrapper(HyDealOrderQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HyDealOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getOrderCode()), HyDealOrder::getOrderCode, bo.getOrderCode());
        lqw.eq(bo.getBuyerId() != null, HyDealOrder::getBuyerId, bo.getBuyerId());
        lqw.eq(bo.getSellerId() != null, HyDealOrder::getSellerId, bo.getSellerId());
        lqw.eq(bo.getSendType() != null, HyDealOrder::getSendType, bo.getSendType());
        lqw.eq(bo.getCreateTime() != null, HyDealOrder::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getUpdateTime() != null, HyDealOrder::getUpdateTime, bo.getUpdateTime());
        lqw.eq(bo.getStatus() != null, HyDealOrder::getStatus, bo.getStatus());
        lqw.orderByDesc(HyDealOrder::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(HyDealOrder add) {
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(HyDealOrder update) {
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(HyDealOrder entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	@Override
	public Long createOrder(HyUser user, HyDealOrder add){
		HyDealGoods goods = dealGoodsService.getById(add.getGoodsId());
		HyUser seller = userService.getById(goods.getUserId());

		// 创建订单
		add.setOrderCode(RandomUtil.randomNumbers(20));
		add.setGoodsId(goods.getGoodsId());
		add.setGoodsName(goods.getGoodsName());
		add.setSellerId(seller.getUserId());
		add.setSellerNickName(seller.getNickName());
		add.setSellerAvatar(seller.getAvatar());
    	add.setBuyerId(user.getUserId());
		add.setBuyerNickName(user.getNickName());
		add.setBuyerAvatar(user.getAvatar());
    	add.setPrice(goods.getPrice());
    	add.setPic(goods.getPic());
    	add.setSendType(goods.getSendType());
    	add.setAddress(add.getAddress());
    	add.setStatus(1);
		this.save(add);

		// 商品状态修改为交易中
		goods.setStatus(2);
		dealGoodsService.updateById(goods);

		return add.getOrderId();
	}

	/**
	 * 取消订单
	 * @param user 操作用户
	 * @param orderId
	 * @return
	 */
	@Override
	public Integer orderCancel(HyUser user, Integer orderId) {
		HyDealOrder order = this.getById(orderId);
		HyDealGoods goods = dealGoodsService.getById(order.getGoodsId());

		if (ObjectUtil.equals(user.getUserId(), order.getBuyerId())) {
			// 7买家取消
			order.setStatus(7);
			// 商品状态修改为发布中
			goods.setStatus(1);
		} else if (ObjectUtil.equals(user.getUserId(), order.getSellerId())) {
			// 6卖家取消
			order.setStatus(6);
			// 0未发布
			goods.setStatus(0);
		}

		dealGoodsService.updateById(goods);

		return baseMapper.updateById(order);
	}

	/**
	 * 确认订单
	 * @param user 操作用户
	 * @param orderId
	 * @return
	 */
	@Override
	public Integer orderConfirm(HyUser user, Integer orderId) {
		HyDealOrder order = this.getById(orderId);
		HyDealGoods goods = dealGoodsService.getById(order.getGoodsId());

		//(1交易中，2交易成功，3交易失败，4卖家确认，5买家确认，6卖家取消，7买家取消)
		if (ObjectUtil.equals(user.getUserId(), order.getBuyerId())) {
			// 5买家确认，直接交易成功
			order.setStatus(2);
		} else if (ObjectUtil.equals(user.getUserId(), order.getSellerId())) {
			// 4卖家确认
			order.setStatus(4);
		}

		// 商品状态修改为已卖出
		goods.setStatus(3);
		dealGoodsService.updateById(goods);

		return baseMapper.updateById(order);
	}
}
